package com.guchenbo.example.socket.nio;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @Author guchenbo
 * @Date 2018/10/26.
 */
public class EchoClient {
    protected static final Logger log = LoggerFactory.getLogger(EchoClient.class);

    public static void main(String[] args) {
        EchoClient client = new EchoClient();
        client.start();
    }

    private void start() {
        try {
            SocketChannel socketChannel = SocketChannel.open();
            boolean conn = socketChannel.connect(new InetSocketAddress(9999));
            socketChannel.configureBlocking(false);
            System.out.println(conn);
            //
            Selector selector = Selector.open();
            socketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);

            while (!Thread.interrupted()) {
                int i = selector.select();
                System.out.println(i);
                if (i > 0) {
                    Set<SelectionKey> keySet = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = keySet.iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
//                                                iterator.remove();
                        SocketChannel channel = (SocketChannel) key.channel();
                        NioUtils.log(key);

                        if (key.isAcceptable()) {

                        } else if (key.isReadable()) {
                            log.info("read");

                            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                            channel.read(byteBuffer);
                        }

                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
